import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ListRawState } from "../../views/home";

interface CarListItem extends ListRawState {
  count: number;
  state: boolean;
}

const carSlice = createSlice({
  name: "car",
  initialState: {
    carList: [] as CarListItem[],
  },
  reducers: {
    // 加入
    addCar(state, action: PayloadAction<CarListItem>) {
      const item = state.carList.find(v => v.id === action.payload.id)
      if(item) item.count++
      else state.carList.push(action.payload)
    },
    // 减少
    subCar(state, action: PayloadAction<CarListItem>) {
      const item = state.carList.find(v => v.id === action.payload.id)
      if(item) item.count--
    },
    // 单个状态改变
    changeState(state, action: PayloadAction<CarListItem>) {
      const item = state.carList.find(v => v.id === action.payload.id)
      if(item) item.state = !item.state
    },
    // 所有状态改变
    changeAllState(state, action: PayloadAction<boolean>) {
      state.carList.forEach(v => v.state = action.payload)
    }
  },
});

export const { addCar, subCar, changeState, changeAllState } = carSlice.actions;

export default carSlice;
